package info.peigen.hotpot.component.raspberrypi.gpio.dht11;

import com.pi4j.context.Context;
import com.pi4j.io.spi.Spi;
import lombok.AccessLevel;
import lombok.experimental.Accessors;
import lombok.experimental.FieldDefaults;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;

/**
 * <b>(HumiTempApp)</b>
 * A simple demo application reading current temperature and humidity from the DHT11 sensor on the CrowPi
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2024/4/27
 */
@SuppressWarnings({"SpellCheckingInspection", "InfiniteLoopStatement"})
@FieldDefaults(level = AccessLevel.PRIVATE)
@Accessors(chain = true)
@Controller
@Mapping("/temperature")
public class HumiTempApp {

    @Inject
    Context pi4j;
    static final int PIN_TEMPERATURE = 23;
    static final int PIN_BUTTON      = 26;

    Spi temperature;

    @Mapping("/")
    public void index(org.noear.solon.core.handle.Context ctx) {
        initTemperature(pi4j);
        //内部跳转到 /index.htm
        // ctx.forward("/raspberry/input/RaspberryPiTemperature.html");
    }

    public void initTemperature(Context pi4j) {
        // Initialize a HumiTempComponent with default values
        final var dht11 = new HumiTempComponent();

        System.out.println("Welcome to the HumiTempApp");
        System.out.println("Measurement starts now.. ");

        // Start some measurements in a loop
        while (true) {
            System.out.println("It is currently " + dht11.getTemperature() + "°C and the Humidity is " + dht11.getHumidity() + "%.");
            delay(1500);
        }
    }

    private void delay(long milliseconds) {
        try {
            Thread.sleep(milliseconds);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
